<template>
  <div>
    <el-card class="box-card" style="height:800px">
      <div slot="header" class="clearfix">
        <span>
          <navigation />
        </span>
        <el-button size="small" style="float: right;" type="primary" @click="addPermiss">添加</el-button>
      </div>
      <el-scrollbar class="page-component__scroll" style="height:100%">
        <div style="height:670px;">
          <el-table
            :data="tableData"
            border
            style="width: 100%"
            highlight-current-row
            height="650px"
            :header-cell-style="{ background: '#f5f5f5' }"
          >
            <el-table-column align="center" type="index" width="50" label="序号"></el-table-column>
            <el-table-column align="center" prop="taskName" label="重点工作"></el-table-column>
            <el-table-column align="center" prop="title" label="标题"></el-table-column>
            <el-table-column align="center" prop="addTime" label="创建时间"></el-table-column>
            <el-table-column align="center" prop="addUserName" label="发布人"></el-table-column>
            <el-table-column align="center" label="操作" width="180">
              <template slot-scope="scope">
                <el-button @click="lookPermiss(scope.row)" type="text">查看</el-button>
                <el-button @click="editPermiss(scope.row)" type="text">修改</el-button>
                <el-button @click="removePermiss(scope.row)" type="text">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-scrollbar>
      <el-pagination
        background
        style="float:right"
        layout="prev, pager, next"
        :page-size="pageSize"
        :current-page="currentPage"
        :total="total"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </el-card>
    <el-dialog
      title="日常工作动态数据操作"
      center
      :visible.sync="dialogschedule"
      width="50%"
      :close-on-click-modal="false"
    >
      <div>
        <el-form ref="form" :model="form" label-width="110px">
          <el-form-item label="重点工作：">
            <!-- <el-input type="text" v-model="form.taskName"></el-input> -->
            <el-cascader
              ref="taskRef"
              class="userIntSize"
              v-model="form.taskId"
              :options="tasksList"
              :props="taskProp"
              :show-all-levels="false"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="标题：">
            <el-input placeholder="请输入标题" type="text" v-model="form.title"></el-input>
          </el-form-item>
          <el-form-item label="内容：">
            <el-input
              type="textarea"
              :autosize="{ minRows: 10, maxRows: 15}"
              placeholder="请输入内容"
              v-model="form.content"
            ></el-input>
          </el-form-item>
          <el-form-item label="附件：" prop="file">
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :on-success="successFile"
              :on-remove="handleDealFileRemove"
              :file-list="fileList"
              :limit="3"
              :on-exceed="handleExceed"
              ref="rebateUpload"
              accept=".jpg, .jpeg, .png, .JPG, .JPEG, .PNG"
              :on-change="uploadChange"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogschedule = false">取 消</el-button>
        <el-button type="primary" @click="dataGrade()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import configJson from "../../api/config";
export default {
  data() {
    return {
      tableData: [],
      dialogschedule: false,
      form: {
        id: "",
        taskId: "", //任务名称
        title: "", //牵头单位
        content: "", //牵头单位,
        fileNames: [],
      },
      uploadUrl: configJson.API_URL + "fileController/uploadFile", //地址
      fileList: [],
      tasksList: [],
      taskProp: {
        label: "name",
        value: "id",
        children: "children",
      },
      arr: [],
      pageSize: 10,
      currentPage: 1,
      total: 0,
    };
  },
  mounted() {
    this.gettasksList();
    this.getData();
  },
  methods: {
    isImage(fileName) {
      if (typeof fileName !== "string") return;
      let name = fileName.toLowerCase();
      return (
        name.endsWith(".png") || name.endsWith(".jpeg") || name.endsWith(".jpg")
      );
    },
    uploadChange(file, fileList) {
      // 拿到当前上传图片的name，判断其后缀名是否符合
      let type = this.isImage(file.name);
      console.log(type);
      this.fileList = fileList;
      let fileLength = this.fileList.length;
      if (!type) {
        // 若不符合图片类型，则让当前上传的文件去除掉即可，即从上传对列删除本次上传
        this.fileList.splice(fileLength - 1, 1);
        this.$message.error("只允许上传图片");
      }
    },
    getData() {
      this.$axios
        .post(`dailyNews/getList/${this.currentPage}/${this.pageSize}`)
        .then((res) => {
          if (res.code == 200) {
            this.tableData = res.data.list;
            this.total = res.data.total;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    gettasksList() {
      this.$axios
        .post("task/getList")
        .then((res) => {
          if (res.code == 200) {
            res.data.map((item) => {
              if (item.children.length == 0) {
                item.children = undefined;
              }
              this.tasksList = res.data;
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    addPermiss() {
      this.form = {
        id: "",
        taskId: "", //任务名称
        title: "", //牵头单位
        content: "", //牵头单位,
        fileNames: [],
      };
      this.fileList = [];
      this.arr = [];
      this.dialogschedule = true;
    },
    successFile(response, file, fileList) {
      console.log(response.data);
      if (response.code == 200) {
        this.fileList = fileList;
        let fileUrlStr = this.uploadUrl.split("/");
        let fileRemoveChl = fileUrlStr.slice(0, fileUrlStr.length - 1);
        this.fileUrlEnd = fileRemoveChl.join("/");
        this.fileName = this.fileUrlEnd + "/" + response.data;
        this.arr.push(response.data);
      }
    },
    handleDealFileRemove(file, fileList) {
      if (file && file.id) {
        this.$axios
          .post(`/fileController/deleteFileLib`, { id: file.id }, 2)
          .then((res) => {
            if (res.code == 200) {
              console.log(res);
              this.$message({
                message: "附件删除成功",
                type: "success",
              });
              this.getData();
            }
          })
          .catch((err) => {
            console.log(err);
          });
        this.fileList = fileList;
        this.fileName = "";
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    lookPermiss(data) {
      this.form.id = data.id;
      this.$router.push({
        path: "/workLookData",
        query: { id: data.id },
      });
    },
    editPermiss(data) {
      this.dialogschedule = true;
      this.form.id = data.id;
      this.form = data;
      this.fileList = data.files;
      this.arr = [];
      this.form.content = this.form.content.replace(/<br\/>/g, "\n");
      this.form.content = this.form.content.replace(/&nbsp/g, " ");
    },
    removePermiss(data) {
      let _obj = {
        id: data.id,
      };
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios
            .post("/dailyNews/remove", _obj, 2)
            .then((res) => {
              if (res.code == 200) {
                // this.getListByPage();
                this.$message({
                  message: "数据更新成功",
                  type: "success",
                });
                this.getData();
              }
            })
            .catch((err) => {
              console.log(err);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    dataGrade() {
      console.log(this.form.content);
      this.form.content = this.form.content.replace(/\n/g, "<br/>");
      this.form.content = this.form.content.replace(/ /g, " &nbsp");
      let taskId = 0;
      if (this.form.taskId.length === 1) {
        taskId = this.form.taskId[0];
      } else {
        taskId = this.form.taskId[1];
      }
      let arr = {
        taskId: taskId,
        title: this.form.title,
        content: this.form.content,
        fileNames: this.arr,
      };
      console.log(this.form.id);
      if (this.form.id === "") {
        console.log(arr);
        this.addSubmit(arr);
      } else {
        arr["id"] = this.form.id;
        this.editSubmit(arr);
      }
    },
    addSubmit(data) {
      this.$axios
        .post(`/dailyNews/add`, data)
        .then((res) => {
          if (res.code == 200) {
            console.log(res);
            this.$message({
              message: "数据添加成功",
              type: "success",
            });
            this.getData();
            this.dialogschedule = false;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    editSubmit(data) {
      this.$axios
        .post(`/dailyNews/update`, data)
        .then((res) => {
          if (res.code == 200) {
            console.log(res);
            this.$message({
              message: "数据添加成功",
              type: "success",
            });
            this.getData();
            this.dialogschedule = false;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getTabList();
    },
  },
};
</script>
<style scoped>
</style>
